from django.shortcuts import render
<<<<<<< HEAD

=======
from django_redis import get_redis_connection
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
>>>>>>> 包克

from apps.question.models import Label, Question, Reply
from apps.question.serializer.labels import LabelsSerializer, LabelSerializerWithQuestionAndArticle
from apps.question.serializer.question import QuestionSerializerForList, QuestionSerializerForCreate, QuestionSerializerForDetail, \
    ReplySerializerForCreate


class LabelsViewSet(ModelViewSet):
    '''获取所有标签信息'''
    queryset = Label.objects.all()

    def get_serializer_class(self):
        '''根据ｐｋ值判断是返回所有标签信息还是单个标签'''
        pk = self.kwargs.get('pk')
        if pk:
            return LabelSerializerWithQuestionAndArticle
        else:
            return LabelsSerializer


    @action(methods=['get'],detail=False)
    def users(self,request):
        '''获取用户关注的标签信息'''

        try:
            user = self.request.user
        except Exception:
            user = None

        if user is None:
            return Response([])

        labels = user.labels.all()
        ser = LabelsSerializer(instance=labels,many=True)
        return Response(ser.data)


    @action(methods=['put'], detail=True)
    def focusin(self,request,pk):
        '''关注标签'''
        try:
            user = self.request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated():
            label = self.get_object()
            if user not in label.users.all():
                label.users.add(user)
                label.save()
                return Response({'success': True, 'message': '关注成功'})
            else:
                return Response({'success': True, 'message': '已经关注了...'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)


    @action(methods=['put'], detail=True)
    def focusout(self,request,pk):
        '''取消关注'''
        try:
            user = self.request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated():
            label = self.get_object()
            if user in label.users.all():
                label.users.remove(user)
                label.save()
                return Response({'success': True, 'message': '取消关注成功'})
            else:
                return Response({'success': True, 'message': '已经取消关注了...'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)



class QuestionViewSet(ModelViewSet):
    '''问答相关'''
    queryset = Question.objects.all()
    serializer_class = QuestionSerializerForList

    def create(self, request, *args, **kwargs):
        '''发布问题'''
        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            request_data = request.data
            print(request_data) # {'content': '<p><em><strong>哈哈哈哈和</strong></em></p>\n', 'title': '十万个为什么？', 'labels': [1]}

            request_data["user"] = user.id
            s = QuestionSerializerForCreate(data=request_data)
            s.is_valid(raise_exception=True)
            s.save()
            return Response({'success': True, 'message': '发表成功'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)


    def retrieve(self, request, *args, **kwargs):
        '''问题详情'''
        question_id = kwargs.get('pk')
        question = Question.objects.get(pk=question_id)

        # 访问量+1
        question.visits += 1
        question.save()

        replies = question.replies.all()
        question.comment_question = []
        question.answer_question = []

        for item in replies:
            if item.type == 0:  # 问题的评论
                question.comment_question.append(item)
            elif item.type == 2:  # 回答的评论
                question.answer_question.append(item)

        s = QuestionSerializerForDetail(instance=question)
        return Response(s.data)





    @action(methods=["GET"], detail=True, url_path="label/new")
    def get_new_question_by_labelid(self, request, pk):
        '''查询labelid为pk的所有问题,按照回复的时间进行降序'''
        if pk == "-1":
            questions = Question.objects.all().order_by("-replytime")
        else:
            label = Label.objects.get(id=pk)
            questions = label.questions.all().order_by("-replytime")
        ser = QuestionSerializerForList(instance=questions, many=True)
        return Response(ser.data)

<<<<<<< HEAD
=======


    @action(methods=["GET"], detail=True, url_path="label/hot")
    def get_hot_question_by_labelid(self,request,pk):
        '''查询labelid为pk的所有问题,按照回复的数量进行降序'''
        if pk == "-1":
            questions = Question.objects.all().order_by("-reply")
        else:
            label = Label.objects.get(id=pk)
            questions = label.questions.all().order_by("-reply")
        ser = QuestionSerializerForList(instance=questions, many=True)
        return Response(ser.data)



    @action(methods=["GET"], detail=True, url_path="label/wait")
    def get_wait_question_by_labelid(self, request, pk):
        '''查询labelid为pk未解答的问题,按照问题创建的时间降序'''
        if pk == "-1":
            questions = Question.objects.all()
        else:
            label = Label.objects.get(id=pk)
            questions = label.questions.all()
        questions = questions.filter(reply=0).order_by("-createtime")
        ser = QuestionSerializerForList(instance=questions, many=True)
        return Response(ser.data)

    @action(methods=['put'], detail=True)
    def useful(self, request, pk):
        '''问题有用'''

        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('question')
            flag = redis_conn.hget("question_userful_%s" % user.id, pk)
            if flag:
                return Response({'success': False, 'message': '请不要重复操作'})
            else:
                question = self.get_object()
                question.useful_count += 1
                question.save()
                redis_conn.hset("question_userful_%s" % user.id, pk, 1)
                return Response({'success': True, 'message': '更新成功'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)



    @action(methods=['put'],detail=True)
    def unuseful(self,request,pk):
        '''问题无用'''

        try:
            user = request.user
        except Exception:
            user = None


        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('question')
            flag = redis_conn.hget('question_unuserful_%s' % user.id, pk)
            if flag:
                return Response({'success':False,'message':'请不要重复操作'})
            else:
                question = self.get_object()
                question.unuseful_count += 1
                question.save()
                redis_conn.hset('question_unuserful_%s' % user.id, pk,1)
                return Response({'success': True, 'message': '更新成功'})

        else:
            return Response({'success': False, 'message': '未登录'}, status=400)


class ReplyViewSet(ModelViewSet):
    queryset = Reply.objects.all()

    def create(self, request, *args, **kwargs):
        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:

            # 接收参数
            request_data = request.data
            request_data["user"] = user.id
            s = ReplySerializerForCreate(data=request_data)
            s.is_valid(raise_exception=True)
            reply = s.save()
            problem = reply.problem
            # 如果是回答,则更新对应的数据
            if request_data.get('type') == 2:
                problem.reply += 1
                problem.replyname = reply.user.username
                problem.replytime = reply.createtime
                problem.save()
            return Response({'success': True, 'message': '发表成功'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)

    @action(methods=['put'], detail=True)
    def useful(self,request,pk):
        '''回答有用'''
        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:

            redis_conn = get_redis_connection('reply')
            flag = redis_conn.hget('reply_userful_%s" % user.id', pk)
            if flag:
                return Response({'success': False, 'message': '请不要重复操作'})
            else:
                reply = self.get_object()
                reply.useful_count += 1
                reply.save()
                redis_conn.hset('reply_userful_%s" % user.id', pk, 1)
                return Response({'success': True, 'message': '更新成功'})

        else:
            return Response({'success': False, 'message': '未登录'}, status=400)


    @action(methods=['put'], detail=True)
    def unuseful(self, request, pk):
        '''回答无用'''
        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:

            redis_conn = get_redis_connection('reply')
            flag = redis_conn.hget('reply_unuserful_%s" % user.id', pk)
            if flag:
                return Response({'success': False, 'message': '请不要重复操作'})
            else:
                reply = self.get_object()
                reply.unuseful_count += 1
                reply.save()
                redis_conn.hset('reply_unuserful_%s" % user.id', pk, 1)
                return Response({'success': True, 'message': '更新成功'})

        else:
            return Response({'success': False, 'message': '未登录'}, status=400)


>>>>>>> 包克
